package apiserver

import (
	"net"

	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	"github.com/marmotedu/log"
)

type grpcAPIServer struct {
	srv     *grpc.Server
	address string
	key     string
	cert    string
}

func (s *grpcAPIServer) Run() {
	listen, err := net.Listen("tcp", s.address)
	if err != nil {
		log.Fatal("failed to listen:%s", zap.String("err", err.Error()))
	}

	opts := make([]grpc.ServerOption, 0)

	if s.key != "" && s.cert != "" {
		cret, err := credentials.NewServerTLSFromFile(s.cert, s.key)
		if err != nil {
			log.Fatal("credentials.NewServerTLSFromFile err: %v", zap.Any("err", err))
		}
		opts = append(opts, grpc.Creds(cret))
	}

	s.srv = grpc.NewServer(opts...)

	// 注册Grpc控制器
	// pb.RegisterAiServer(s.srv, aictl.New(store.Client()))

	go func() {
		if err := s.srv.Serve(listen); err != nil {
			log.Fatal("failed to start grpc server:%s", zap.String("err", err.Error()))
		}
	}()

	log.Infof("start grpc server at %s", s.address)
}

func (s *grpcAPIServer) Close() {
	s.srv.GracefulStop()
	log.Infof("GRPC server on %s stopped", s.address)
}
